package com.yunban.project.api.word_parse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author: lijiajun
 * @date: 2024-10-24
 * @version: 1.0
 */
@Slf4j
@Component
public class WordParseUtils {

    private static RestTemplate restTemplate;

    @Resource
    public void setRestTemplate(RestTemplate restTemplate) {
        WordParseUtils.restTemplate = restTemplate;
    }
    private final static String PARSE_URL = "https://java.maxing.cn/sa-api/web-api/parse";

    public JSONArray parse(MultipartFile file) {
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        // 添加文件资源
        body.add("file", file.getResource());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        try {
            ResponseEntity<String> resultStr = restTemplate.postForEntity(PARSE_URL, requestEntity, String.class);
            log.info("resultStr.getBody():{}", resultStr.getBody());
            // 將 resultStr.getBody() 转为 List<ParseResp>
            JSONObject resultJson = JSON.parseObject(resultStr.getBody());
            if (ObjectUtils.isEmpty(resultJson)) {
                return null;
            }
            Object result = resultJson.get("data");
            log.info("resultJson:{}", resultJson);
            return JSON.parseArray(JSON.toJSONString(result));
        } catch (Exception ex) {
            log.error("解析失败", ex);
            throw new BusinessException("解析失败:" + ex.getMessage());
        }
    }
}
